package com.ia.aistream.manager.operating.util;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.ia.aistream.common.exception.base.CustomException;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.spring.SpringUtils;
import com.ia.aistream.manager.framework.util.ShiroUtils;
import com.ia.aistream.manager.operating.conf.DocMapConf;
import com.ia.aistream.manager.operating.conf.DocMessageConf;
import com.ia.aistream.manager.operating.util.style.DocStyleUtil;
import com.ia.aistream.manager.operating.util.style.DocTableStyle;
import com.ia.aistream.manager.operating.util.tools.DocToolUtil;
import com.ia.aistream.manager.operating.util.tools.WmfToPngUtilTest2;
import com.ia.aistream.mapper.operating.DocIndexMapper;
import com.ia.aistream.model.operating.dto.ColumnStyle;
import com.ia.aistream.model.operating.dto.ParagraphTextStyle;
import com.ia.aistream.model.operating.dto.PgInfo;
import com.ia.aistream.model.operating.dto.TextInfo;
import com.ia.aistream.model.operating.dto.convert.ConvertDto;
import com.ia.aistream.model.operating.dto.convert.EquOperInfo;
import com.ia.aistream.model.operating.dto.convert.LocationInfo;
import com.ia.aistream.model.operating.dto.convert.SystemEquInfo;
import com.ia.aistream.model.operating.entity.DocContentTable;
import com.spire.doc.*;
import com.spire.doc.collections.DocumentObjectCollection;
import com.spire.doc.collections.ParagraphCollection;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.collections.TableCollection;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.documents.StyleType;
import com.spire.doc.fields.*;
import com.spire.doc.formatting.Border;
import com.spire.doc.formatting.ListFormat;
import com.spire.doc.interfaces.IDocumentObject;
import com.spire.doc.packages.sprqmc;
import org.w3c.dom.DocumentType;
import sun.misc.BASE64Encoder;

import javax.print.Doc;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DataTest {
//    public static void main(String[] args) {
//
//        List<String> oplist = new ArrayList<>();
//        oplist.add("开启");
//        oplist.add("关闭");
//        oplist.add("流量");
//        oplist.add("开度");
//        oplist.add("调节");
//        oplist.add("启动");
//        oplist.add("达到");
//        oplist.add("加压");
//
//        // 表示参数字典表
//        List<String> argList = new ArrayList<>();
//        argList.add("m3/h");
//        argList.add("MPa");
//        argList.add("Mpa");
//        argList.add("℃");
//        argList.add("us/cm");
//        argList.add("ug/L");
//        argList.add("圈");
//        argList.add("%");
//        argList.add("bar.a");
//        argList.add("bar");
//        argList.add("KPa.g");
//        argList.add("KPa");
//        argList.add("kPa");
//        argList.add("（红刻度线以上）");
//        argList.add("A");
//        argList.add("mm/s");
//        argList.add("mm");
//        argList.add("μg/kg");
//        argList.add("mm／sec");
//        argList.add("m³/h");
//
//
//
//        // 表示逻辑运算符字典表
//        List<String> logicOp = new ArrayList<>();
//        logicOp.add("左右");
//        logicOp.add("到达");
//        logicOp.add("约");
//        logicOp.add("接近");
//        logicOp.add("≤");
//        logicOp.add("<");
//        logicOp.add("=");
//        logicOp.add(">=");
//        logicOp.add("＞");
//        logicOp.add("＜");
//        logicOp.add("~");
//        logicOp.add("=");
//
//
//        String s6 ="定值设定为980 m³/h（1台泵运行流量大于490 m³/h可以满足）";
//        String s7 = "< 6.3mm/s";
//        String s8 = "105 KT—110 KT";
//        String s10 = "\uF09E 可利用025VL/026VL的前隔离阀006/009VL及旁路阀011VL进行调节";
//        String s9 = "\uF02D 在凝结水泵出口处氧含量： ＜50μg/kg";
//        String s13 = "凝结水泵001PO/002/003PO置于手动";
//        String s12 = "\uF02D 要求现场检查002/003/001PO的机械密封水压力正常";
//        String s11 = "MX-7.5米";
//        String s15= "\uF02D 现场检查3台凝结水泵机械密封水压力（1CEX103LP、1CEX230LP、1CEX303LP）正常（0.1-0.8MPa）";
//        String s14 = "002 JA 1";
//        String s16 = "001 MD/L";
//        String s17 = "整定值：49-51℃";
//        String s19 = "运行：48-58℃，启动时偏低";
//        String s18 = "250-400mm";
//
//
//        String s20 = "CRF145-1MT≥90℃";
//        String tableCellContent = "280±30mm";
//        String s21 = "101、103、105、107、109、111 RS";
//        String s22 = "289.4℃<T<294.4℃";
//        String s23 = "15.3MPa<P<15.5MPa";
////        LocationInfo location = DocHandleBusiness.getLocation(s11);
////        System.out.println(location);
//
//        EquOperInfo equOperInfo = DocHandleBusiness.geteqOpContent(oplist, argList, logicOp, tableCellContent);
//        System.out.println(equOperInfo);
//        List<String> eq = new ArrayList<>();
////        if(DocHandleBusiness.isDunHao(tableCellContent)){
////            tableCellContent = tableCellContent.replace("、", "/");
////        }
//
//        if(DocRegularUtil.isNumOther(tableCellContent)){
//            tableCellContent = tableCellContent.replace("、", "/");
//        }
////        // 处理系统设备编码含有‘-’和‘/’分割的情况,将设备按照、拼接
//        if(DocRegularUtil.isNeedEquipment(tableCellContent)){
//            if(tableCellContent.contains("-")){
//                List<String> list = DocHandleBusiness.handleHorizontalBar(tableCellContent);
//                eq.addAll(list);
//            }else{
//                List<String> list = DocHandleBusiness.handleSlantingBar(tableCellContent);
//                eq.addAll(list);
//            }
//        }else if(isTwoEqu(tableCellContent)){
//            List<String> twoEqu = DocHandleBusiness.getTwoEqu(tableCellContent);
//            eq.addAll(twoEqu);
//        }else {
//            // 处理段落中的系统
//            List<String> list = DocHandleBusiness.handleContentEquipment(tableCellContent);
//            if(list!=null && list.size()>0){
//                eq.addAll(list);
//            }
//        }
//
//        System.out.println(eq);
//    }
//
//    private static boolean isTwoEqu(String msg){
//       msg =  msg.replace(" ", "");
//        String equPattern = "^.*\\d{3,4}[A-Z]+—\\d{3,4}[A-Z]+.*$";
//        Pattern equR = Pattern.compile(equPattern);
//        Matcher equM = equR.matcher(msg);
//
//        return equM.matches();
//    }

//    public static void main(String[] args) {
//        String fileName = "D:\\a\\验证后文件\\FQ1-CET-TPOPNR-0001汽机轴封系统运行规程_002.doc";
//        DocToolUtil.docToHtml(fileName);
//    }
    public static void main(String[] args) throws Exception {
        // 获取段落的样式
        String fileName = "D:\\a\\check.doc";
        Document document = new Document();
        document.loadFromFile(fileName);

        SectionCollection sections = document.getSections();

        for (int i=0; i<sections.getCount(); i++){
            Section section = sections.get(i);
            DocumentObjectCollection childObjects = section.getBody().getChildObjects();
            for (int j=0; j<childObjects.getCount(); j++){
                if(childObjects.get(j).getDocumentObjectType().equals(DocumentObjectType.Table)){
                    System.out.println("表格==");
                    Table table = (Table) childObjects.get(j);

                    getTable(table);
                }else if(childObjects.get(j).getDocumentObjectType().equals(DocumentObjectType.Paragraph)){
                    Paragraph paragraph = (Paragraph)childObjects.get(j);
                    getPara2(paragraph);
                }
            }

        }
    }


    public static void getPara2(Paragraph paragraph) throws Exception {

        String trim = paragraph.getText().trim();
        if(!StringUtils.isEmpty(trim)){
            System.out.println(trim);
        }

    }

    /***
     * 获取文本框中的内容
     * @param textBox
     * @return
     */
    public static String getTextBox(TextBox textBox){
        StringBuilder sb = new StringBuilder();
        ParagraphCollection paragraphs = textBox.getBody().getParagraphs();
        for (int i=0; i<paragraphs.getCount(); i++){
            Paragraph paragraph = paragraphs.get(i);
            String content = paragraph.getListText().trim() + "  " + paragraph.getText().trim();
            sb.append(content.trim());
        }

        return sb.toString();
    }
    public static void getTable(Table table) throws Exception{
        for (int r=0; r<table.getRows().getCount(); r++){
            for (int c=0; c<table.getRows().get(r).getCells().getCount(); c++){
                TableCell tableCell = table.getRows().get(r).getCells().get(c);

                // 行合并
//                Integer rowsMerge = DocTableStyle.getRowsMerge(table, r, c);
//                System.out.println(rowsMerge + "----" + tableCell.getParagraphs().get(0).getText());
                // 列和并
                Integer colsMerge = DocTableStyle.getColsMerge(table, r, c, 5);
                System.out.println(colsMerge + "----" + tableCell.getParagraphs().get(0).getText());
            }
        }
    }

    /***
     * 实现表格数据的解析
     * @param table
     */
    public static void getTable2(Table table){

        for (int r=0; r<table.getRows().getCount(); r++){
            for (int c=0; c<table.getRows().get(r).getCells().getCount(); c++){
                TableCell tableCell = table.getRows().get(r).getCells().get(c);
                for(int p=0; p<tableCell.getParagraphs().getCount(); p++) {
                    Paragraph paragraph = tableCell.getParagraphs().get(p);
                    for(int o=0; o<paragraph.getChildObjects().getCount(); o++){
                        DocumentObject object = paragraph.getChildObjects().get(o);
                        if(object instanceof TextRange){
                            TextRange range = (TextRange) object;
                            System.out.println(range.getText());
                            System.out.println("\tgetFontName=" + range.getCharacterFormat().getFontName());
                            System.out.println("\tgetFontNameFarEast=" + range.getCharacterFormat().getFontNameFarEast());
                            System.out.println("\tgetFontNameNonFarEast=" + range.getCharacterFormat().getFontNameNonFarEast());
                        }
                    }
                    System.out.println();
                }
            }
        }
    }
    public static int getPara(Paragraph paragraph, int index) throws Exception {

        for (int o=0; o<paragraph.getChildObjects().getCount(); o++){
            DocumentObject object = paragraph.getChildObjects().get(o);
            System.out.println(object);
            if(object instanceof DocPicture){
                System.out.println("===========================");
                DocPicture docPicture = (DocPicture) object;
//                getPicture(docPicture);
                String path = "d:\\a\\svg\\"+ UUID.randomUUID() + "_" + index +".wmf";

                DocToolUtil.downloadImages(docPicture, path);
                WmfToPngUtilTest2.convert2(path);
//                String img = WmfToPngUtilTest2.convert(path);
//               +==" + docPicture.getHeight() + "\t" + s);
            }else if(object instanceof DocOleObject){
                DocOleObject docOleObject = (DocOleObject)object;
                DocPicture olePicture = docOleObject.getOlePicture();
                String path = "d:\\a\\svg\\"+ UUID.randomUUID() + "_" + index +".wmf";
                DocToolUtil.downloadImages(olePicture, path);
                String img = WmfToPngUtilTest2.convert2(path);
//                System.out.println(img + "++==" + olePicture.getHeight());
            }
        }

        index++;
        return index;
    }

    public static void getPicture(DocPicture docPicture){
        String s = docPicture.getStyleName();
        System.out.println("getStyleName=" + s);

        String getShapeType = docPicture.getShapeType().toString();
        System.out.println("getShapeType=" + getShapeType);

        String getTitle = docPicture.getTitle();
        System.out.println("getTitle=" + getTitle);

        String alternativeText = docPicture.getAlternativeText();
        System.out.println("alternativeText=" + alternativeText);
//
        System.out.println(docPicture.getRotationEx());
        System.out.println(docPicture.getImage().getType());
    }
    public static void getStyle(Paragraph paragraph) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        ParagraphTextStyle paragraphStyle = new ParagraphTextStyle();
        PgInfo pgInfo = new PgInfo();
        pgInfo.setPgAlign(paragraph.getFormat().getHorizontalAlignment().toString());

        // 获取该段落的对象数
        int charCount = paragraph.getChildObjects().getCount();

        // 记录列表数据样式
        String listText = paragraph.getListText().trim();
        String trim = paragraph.getText().trim();

        // 记录段落的样式
        List<TextInfo> textInfoList = new ArrayList<>();

        // 记录图片对象
        String imgStr = "";
        for(int i=0; i<charCount; i++) {
            boolean flag = true;
            // 内容样式
            TextInfo textInfo = new TextInfo();

            if(i==0 && !StringUtils.isEmpty(listText)){
                textInfo.setListContent(URLEncoder.encode(listText, "utf-8"));
                textInfo.setListFontName(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontName());
            }

            ParagraphBase paragraphBase = paragraph.get(i);
            if (paragraphBase instanceof TextRange) {
                // 获取段落对象
                TextRange range = (TextRange) paragraphBase;
                String content = range.getText();
                content = content.replace("<", "&lt;");
                content = content.replace(">", "&gt;");
                if(paragraph.get(i).getCharacterFormat().getUnderlineStyle().toString().equals("Single")){
                    flag = false;
                    TextInfo textInfo1 = textInfoList.get(textInfoList.size() - 1);
                    if(textInfo1.getUnderLine()!=null && StringUtils.isEmpty(textInfo1.getContent())){
                        continue;
                    }
                    if(StringUtils.isEmpty(content)){
                        textInfo.setUnderLine(1);
                    }else{
                        textInfo.setUnderLine(2);
                    }
                }
                // 记录文字内容
                if(flag){
                    content = content.replace("\t", "&nbsp;&nbsp;");
                    content = content.replace(" ", "&nbsp;");
                }
                // 判断是否为角标
                if (range.getCharacterFormat().getSubSuperScript().toString().equals("Sub_Script")){
                    content = "<sub style='font-size: 1px'>" + content +"</sub>";
                }else if(range.getCharacterFormat().getSubSuperScript().toString().equals("Super_Script")){
                    content = "<sup style='font-size: 1px'>" + content +"</sup>";
                }

                textInfo.setContent(content);
                // 记录字体是否加粗
                textInfo.setBold(paragraph.get(i).getCharacterFormat().getBold());
                // 设置文字字体
//                textInfo.setFontName(paragraph.get(i).getCharacterFormat().getFontName());
                textInfo.setFontName(paragraph.get(i).getCharacterFormat().getFontNameFarEast());
                // 设置字号
                textInfo.setFontSize(paragraph.get(i).getCharacterFormat().getFontSize());

            }

//            if(!StringUtils.isEmpty(textInfo.getContent()) || textInfo.getUnderLine()!=null || !StringUtils.isEmpty(textInfo.getListContent())
//                    || !StringUtils.isEmpty(textInfo.getImgAddress())){
            if(textInfo.getContent()!=null || textInfo.getUnderLine()!=null || !StringUtils.isEmpty(textInfo.getListContent())
                    || !StringUtils.isEmpty(textInfo.getImgAddress())){
                textInfoList.add(textInfo);
            }
        }
        paragraphStyle.setPgInfo(pgInfo);
        paragraphStyle.setTextInfoList(textInfoList);
        map.put(DocMapConf.DOC_PARAGRAPH_STYLE.value, paragraphStyle);
        System.out.println(paragraphStyle);
    }

    private static char[] HEX_VOCABLE = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    public static String bytesToHex(byte[] bs) {

        StringBuilder sb = new StringBuilder();
        for (byte b : bs) {
            int high = (b >> 4) & 0x0f;
            int low = b & 0x0f;
            sb.append(HEX_VOCABLE[high]);
            sb.append(HEX_VOCABLE[low]);
        }
        return sb.toString();
    }

    public static String bytesToHexString(byte[] bArr) {
        StringBuffer sb = new StringBuffer(bArr.length);
        String sTmp;

        for (int i = 0; i < bArr.length; i++) {
            sTmp = Integer.toHexString(0xFF & bArr[i]);
            if (sTmp.length() < 2){
                sb.append(0);
            }
            sb.append(sTmp.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16);
            j++;
        }
        return result;
    }
    public static void downloadImages(DocPicture docPicture, String path) throws IOException {

        byte[] bytes = docPicture.getImageBytes();
        File file = new File(path);
        FileOutputStream fis = new FileOutputStream(file);
        fis.write(bytes);
        fis.close();
    }

    
   
}
